package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.lettuce.core.RedisClient;
import org.apache.commons.lang.ObjectUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class ManageServiceImpl implements ManageService {
    //调用mapper层

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private SpuInfoMapper  spuInfoMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    private SpuImageMapper spuImageMapper;

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private SpuPosterMapper spuPosterMapper;

    @Autowired
    private  SkuInfoMapper skuInfoMapper;

    @Autowired
    private  SkuImageMapper skuImageMapper;

    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public List<BaseCategory1> getCategory1() {
        //  select * from base_category1
        return baseCategory1Mapper.selectList(null);
    }

    @Override
    public List<BaseCategory2> getCategory2(long category1Id) {
        //  select * from base_category2 where category1_id = category1Id
        QueryWrapper<BaseCategory2> baseCategory2QueryWrapper = new QueryWrapper<>();
        baseCategory2QueryWrapper.eq("category1_id",category1Id);
        return baseCategory2Mapper.selectList(baseCategory2QueryWrapper);
    }
    @Override
    public List<BaseCategory3> getCategory3(long category2Id) {
        //select * from base_category3 where category2_id = category2Id
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>().eq("category2_id",category2Id));

    }
    @Override
    public List<BaseAttrInfo> getattrInfoList(long category1Id, long category2Id, long category3Id) {
        //  根据分析可能需要具备的知识点：mybatis的动态sql 标签！
        //  多表关联查询：因此 使用*Mapper.xml
        //  开发的默认规则： service 层 ；get  save mapper层；select insert
        return baseAttrInfoMapper.selectAttrInfoList(category1Id,category2Id,category3Id) ;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)//有异常就回滚
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //这张表既可以添加数据也可以修改数据
        if (baseAttrInfo.getId()==null){
            //开始插入数据
            baseAttrInfoMapper.insert(baseAttrInfo);
        }else {
            //修改数据
            baseAttrInfoMapper.updateById(baseAttrInfo);
        }
        //要先删除再新增
        QueryWrapper<BaseAttrValue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_id",baseAttrInfo.getId());
        baseAttrValueMapper.delete(queryWrapper);
        //获取平台属性值集合数据
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        //for循环
        for (BaseAttrValue baseAttrValue :attrValueList) {
            // attrId 传递的时候是null
            baseAttrValue.setAttrId(baseAttrInfo.getId());
            baseAttrValueMapper.insert(baseAttrValue);
        }
    }

    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        //直接返回数据
        return baseAttrValueMapper.selectList(new QueryWrapper<BaseAttrValue>().eq("attr_id",attrId));
    }

    @Override
    public BaseAttrInfo getBaseAttrInfo(Long attrId) {
        //  select * from base_attr_info where id = attrId;
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);
        //给attrValueList赋值
        if (baseAttrInfo!=null){
            baseAttrInfo.setAttrValueList(getAttrValueList(attrId));
        }
        //返回数据
        return baseAttrInfo;
    }

    @Override
    public IPage getSpuInfoPage(Page<SpuInfo> pageParam, SpuInfo spuInfo) {
        QueryWrapper<SpuInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category3_id",spuInfo.getCategory3Id());
        queryWrapper.orderByDesc("id");
        return  spuInfoMapper.selectPage(pageParam,queryWrapper);
    }

    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
    return spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id",spuId));
    }

    @Override
    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
        //调用mapper 多表关联
        return spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {
  /*
        spuInfo;
        spuImage;
        spuSaleAttr;
        spuSaleAttrValue;
        spuPoster
     */ //  获取到spuImage 集合数据
        spuInfoMapper.insert(spuInfo);
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (!CollectionUtils.isEmpty(spuImageList)){
            for (SpuImage spuImage : spuImageList) {
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            }
        }
        //  获取销售属性集合
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (!CollectionUtils.isEmpty(spuSaleAttrList)){
            for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);
                //再次获取销售属性值集合
                List< SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                //判断
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)){
                    //循环遍历
                    for (SpuSaleAttrValue spuSaleAttrValue : spuSaleAttrValueList) {
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    }
                }
            }
        }
        //获取到posterList 集合数据
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();
        //判断不为空
        if (!CollectionUtils.isEmpty(spuPosterList)){
            for (SpuPoster spuPoster : spuPosterList) {
                //赋值
                spuPoster.setSpuId(spuInfo.getId());
                //保存
                spuPosterMapper.insert(spuPoster);
            }
        }
    }

    @Override
    @Transactional( rollbackFor = Exception.class)
    public void saveSkuInfo(SkuInfo skuInfo) {
         /*
            将数据插入数据库表！
            skuInfo:	库存单元表！	记录是哪个spu下的sku!
            skuImage:	库存单元图片表!
            skuSaleAttrValue;	sku 与 销售属性值中间表！
            skuAttrValue:	sku 与平台属性值中间表！
         */
         skuInfoMapper.insert(skuInfo);
         //获取skuImage集合
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        //判断
        if(!CollectionUtils.isEmpty(skuImageList)){
            skuImageList.stream().forEach(skuImage -> {
                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            });
        }
        //skuSaleAttrValue
        if (!CollectionUtils.isEmpty(skuInfo.getSkuAttrValueList())){
            skuInfo.getSkuAttrValueList().stream().forEach(skuAttrValue ->{
                skuAttrValue.setSkuId(skuInfo.getId());
                //  应该能够获取到平台属性名，平台属性值名！
                //  应该页面自动获取！   查询：category3Id 查询到平台属性名！但是绝对找不到要给的属性值名称！
                //  经过分析：可以不用赋值attrName valueName;
                skuAttrValueMapper.insert(skuAttrValue);
            });
        }
        //  skuSaleAttrValue
        if (!CollectionUtils.isEmpty(skuInfo.getSkuSaleAttrValueList())){
            skuInfo.getSkuSaleAttrValueList().stream().forEach(skuSaleAttrValue -> {
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            });
        }
    }

    @Override
    public IPage getList(Page<SkuInfo> skuInfoPage) {
        QueryWrapper<SkuInfo> skuInfoQueryWrapper = new QueryWrapper<>();
        skuInfoQueryWrapper.orderByDesc("id");
        return skuInfoMapper.selectPage(skuInfoPage,skuInfoQueryWrapper);
    }


    @Override
    @Transactional
    public void onSale(Long skuId) {
        //先更改销售状态
        SkuInfo skuInfoUp = new SkuInfo();
        skuInfoUp.setId(skuId);
        skuInfoUp.setIsSale(1);
        skuInfoMapper.updateById(skuInfoUp);
    }

    @Override
    @Transactional
    public void cancelSale(Long skuId) {
    //更改销售状态
        SkuInfo skuInfoUp = new SkuInfo();
        skuInfoUp.setId(skuId);
        skuInfoUp.setIsSale(0);
        skuInfoMapper.updateById(skuInfoUp);
    }

    @Override
    @GmallCache(prefix = "sku:")
    public SkuInfo getSkuInfo(Long skuId) {

        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        //根据skuId 查询图片列表集合
        QueryWrapper<SkuImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sku_id",skuId);
        List<SkuImage> skuImageList =  skuImageMapper.selectList(queryWrapper);
        skuInfo.setSkuImageList(skuImageList);
        return skuInfo;
    }

    @Override
    @GmallCache(prefix = "CategoryView:")
    public BaseCategoryView getCategoryName(Long category3Id) {

        return  baseCategoryViewMapper.selectById(category3Id);

    }

    @Override
    public BigDecimal getSkuPrice(Long skuId) {
        //  select price from sku_info where id = skuId;
        //  select * from sku_info where id = skuId;
        //  SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        //  不需要将数据放入缓存！
        RLock lock = redissonClient.getLock(skuId + ":lock");
        //上锁
        lock.lock();
        SkuInfo skuInfo = null;
        BigDecimal price = new BigDecimal(0);

        try {
            QueryWrapper<SkuInfo> skuInfoQueryWrapper = new QueryWrapper<>();
            skuInfoQueryWrapper.eq("id",skuId);
            skuInfoQueryWrapper.select("price");
            skuInfo = skuInfoMapper.selectOne(skuInfoQueryWrapper);
            if (skuInfo!=null){
                price = skuInfo.getPrice();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        lock.unlock();
        //返回价格
        return skuInfo.getPrice();
    }

    @Override
    @GmallCache(prefix = "SpuSaleAttrListById:")
    public List<SpuSaleAttr> getSpuSaleAttrListById(Long skuId, Long spuId) {

        return spuSaleAttrMapper.selectSpuSaleAttrListById(skuId,spuId);

    }

    //根据spuId查询map集合属性
    @Override
    @GmallCache(prefix = "ValueIdsAndSkuIdToMap:")
    public Map getValueIdsAndSkuIdToMap(Long spuId) {
        Map<Object, Object> map = new HashMap<>();
        List<Map> mapList = skuSaleAttrValueMapper.selectValueIdsAndSkuIdToMap(spuId);
        if (mapList!= null && mapList.size()>0){
            //开始循环遍历
            for (Map skuMap : mapList) {
                map.put(skuMap.get("value_ids"),skuMap.get("sku_id"));
            }
        }
        return map;
    }

    //根据spuId 获取海报数据
    @Override
    public List<SpuPoster> findSpuPosterBySpuId(Long spuId) {
        //  select * from spu_poster where spu_id = spuId;
        return spuPosterMapper.selectList(new QueryWrapper<SpuPoster>().eq("spu_id",spuId));
    }
    /**
     * 从数据库中获取数据
     * @param skuId
     * @return
     */
    private SkuInfo getSkuInfoDB(Long skuId) {
        //  获取skuInfo
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);

        //  判断skuInfo 是否为空！
        if (skuInfo !=null){
            //  需要skuImageList
            List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId));

            skuInfo.setSkuImageList(skuImageList);
        }

        return skuInfo;
    }

    @Override
    @GmallCache(prefix = "BaseAttrInfoList:")
    public List<BaseAttrInfo> getBaseAttrInfoList(Long skuId) {
        //  根据skuId 获取数据
        return baseAttrInfoMapper.selectBaseAttrInfoList(skuId);
    }

    @Override
    public List<JSONObject> getBaseCategoryList() {
        //声明一个集合
        ArrayList<JSONObject> list = new ArrayList<>();
        //一二三级分类数据
        //获取到所有的分类数据 base——category——view
        List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(null);
        // 按照一级分类id 进行分组
        Map<Long, List<BaseCategoryView>> baseCategory1Map = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        //声明一个index遍历
        int index = 1;
        //循环遍历这个map集合
        Iterator<Map.Entry<Long,List<BaseCategoryView>>> iterator = baseCategory1Map.entrySet().iterator();
        while (iterator.hasNext()){
            //创建一个对象
            JSONObject category1 = new JSONObject();
            //获取到Entry对象
            Map.Entry<Long,List<BaseCategoryView>> entry = iterator.next();
            Long category1Id = entry.getKey();
            List<BaseCategoryView> baseCategoryViewList1 = entry.getValue();
            //一级分类Id
            category1.put("categoryId",category1Id);
            //一级分类名称
            category1.put("categoryName",baseCategoryViewList1.get(0).getCategory1Name());
            //表示一级分类的第几项
            category1.put("index",index);
            //一级分类下还有categoryChild, 必须知道二级分类数据集合
            // index 迭代
            index++;
            //获取一级分类下的二级分类数据
            Map<Long,List<BaseCategoryView>> baseCategory2Map = baseCategoryViewList1.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            //循环遍历
            Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator1 = baseCategory2Map.entrySet().iterator();
            //声明一个存储二级分类数据集合
            List<JSONObject> category2Child = new ArrayList<>();
            while (iterator1.hasNext()){
                //创建一个对象
                JSONObject category2 = new JSONObject();
                Map.Entry<Long, List<BaseCategoryView>> entry1 = iterator1.next();
                List<BaseCategoryView> baseCategoryViewList2 = entry1.getValue();
                Long category2Id = entry1.getKey();
                //赋值二级分类Id
                category2.put("categoryId",category2Id);
                //赋值二级分类name
                category2.put("categoryName",baseCategoryViewList2.get(0).getCategory2Name());
                //存储二级分类数据
                category2Child.add(category2);
                //创建一个集合存储三级分类数据
                ArrayList<JSONObject> category3Child = new ArrayList<>();
                //获取三级分类数据
                baseCategoryViewList2.forEach(baseCategoryView -> {
                    //创建一个对象
                    JSONObject category3 = new JSONObject();
                    category3.put("categoryId",baseCategoryView.getCategory3Id());
                    category3.put("categoryName",baseCategoryView.getCategory3Name());
                    category3Child.add(category3);
                });
                //将三级分类数据保存到二级分类数据中
                category2.put("categoryChild",category3Child);
            }
            //将二级分类数据保存到一级
            category1.put("categoryChild",category2Child);
            //将一级分类数据添加到集合中
            list.add(category1);
        }

        //最后返回数据
        return list;
    }

    //使用redis 做分布式锁一
    @GmallCache()
    private SkuInfo getSkuInfoRedisson(Long skuId) {
        //判断缓存中是否有数据 直接从缓存中获取 能够获取说明有数据 否则就没有数据
        try {
            //定义缓存的key
            String skuKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
            SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);
            //  判断
            if (skuInfo == null) {
                //  走数据库+加锁！
                String lockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
                RLock lock = redissonClient.getLock(lockKey);
                //  加上锁
                boolean result = false;
                    result = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                    if (result) {
                        try {
                            //执行业务逻辑
                            skuInfo = getSkuInfoDB(skuId);
                            //防止缓存穿透
                            if (skuInfo == null) {
                                SkuInfo skuInfo1 = new SkuInfo();
                                this.redisTemplate.opsForValue().set(skuKey, skuInfo1, RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
                                return skuInfo1;
                            }
                            //数据库中有数据
                            this.redisTemplate.opsForValue().set(skuKey, skuInfo, RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
                            return skuInfo;
                        } finally {
                            lock.unlock();
                        }
                    } else {
                        //没有获取到锁的人
                        try {
                            Thread.sleep(100);
                            return getSkuInfo(skuId);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }else{
                    //缓存中有数据 直接返回
                    return skuInfo;
                }
            } catch(InterruptedException e){
                //  记录日志.....
                e.printStackTrace();
            }
            return getSkuInfoDB(skuId);
            }

    private SkuInfo getSkuInfoByRedisLua(Long skuId){
        //定义缓存的key sku：skuid： info
       String skuKey =  RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;

       try {
           SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);
           //判断
           if (skuInfo==null){
               //说明缓存中没有数据， 查询数据库 并且添加分布式锁的业务逻辑
               //redis +lua
               String uuid = UUID.randomUUID().toString();
               //加锁
               //定义一个锁的key
               String lockKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
               Boolean flag = this.redisTemplate.opsForValue().setIfAbsent(lockKey, uuid, RedisConst.SKULOCK_EXPIRE_PX1, TimeUnit.SECONDS);
               //flag = true 等于获取了锁
               if (flag){
                   //执行业务逻辑
                   skuInfo = getSkuInfoDB(skuId);
                   //防止缓存穿透
                   if (skuInfo ==null){
                       SkuInfo skuInfo1 = new SkuInfo();
                       this.redisTemplate.opsForValue().set(skuKey,skuInfo1,RedisConst.SKUKEY_TIMEOUT,TimeUnit.SECONDS);
                       return skuInfo1;
                   }
                   //数据库中有数据
                   this.redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
                   //删除锁对象
                   //这边一个lua脚本
                   String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

                   DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                   //存储lua脚本
                   redisScript.setScriptText(script);
                   redisScript.setResultType(Long.class);
                   this.redisTemplate.execute(redisScript, Arrays.asList(lockKey),uuid);
                   return skuInfo;
               }else {
                   //没有获取到锁的人！
                   try {
                       Thread.sleep(1000);
                       //自旋
                       return getSkuInfo(skuId);
                   }catch (InterruptedException e){
                       e.printStackTrace();
                   }
               }
           }else {
               //缓存不为空
               return skuInfo;
           }
       }catch (Exception e){
           //记录日志信息
           e.printStackTrace();
       }
       //表示获取数据库中国的数据
        return  getSkuInfoDB(skuId);
    }

}
